package cn.fulong.frame.config;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.json.XML;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

public class Platform {
    private ApplicationContext applicationContext = null; // 应用上下文
    private Date startupTime;// 容器启动时间
    private static Platform instance = new Platform(); //单例
    private Map<String, Map> webpages = new HashMap<>();

    private Map<String, Map<String, String>> allDicData = new HashMap<>();  //key1=dic_type,key2=dic_code
    private Map<String, List<Map<String, Object>>> allDicList = new HashMap<>(); //key=dic_type

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public static Platform getInstance() {
        return instance;
    }

    private Platform() {
    }

    public void init(ServletContext context) throws Exception {

        WebApplicationContextUtils.getRequiredWebApplicationContext(context)
                .getAutowireCapableBeanFactory().autowireBean(this);
        ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
        this.applicationContext = ctx;
        this.startupTime = new Date();

    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //应用启动时间
    public Date getStartupTime() {
        return startupTime;
    }

    //获取服务类
    public Object getBean(String beanName) {
        return this.applicationContext.getBean(beanName);
    }

    //读取单个配置文件
    private List<String> readFile(String filename) {
        InputStream is = this.getClass().getResourceAsStream(filename);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = "";
        List<String> lines = new ArrayList<>();
        int i = 0;
        try {
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lines;
    }

    public Map getWebPage(String code) {
        return webpages.get(code);
    }


    //获取数据字典某个具体值
    public String getDicValue(String tableName, String code) {
        return allDicData.get(tableName).get(code);
    }

    //获取字典列表List<Map<String, String>>
    public List getDicList(String tableName) {
        return allDicList.get(tableName);

    }
}
